<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
    draggable
  >
    <el-form
      ref="formRef"
      label-width="100px"
      :model="formData"
      :rules="state.formRules"
    >
      <el-row>
        <el-col :span="18">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户类别:" prop="userType">
                <DictSelect
                  ref="userTypeRef"
                  v-model:defaultValue="formData.userType"
                  dict-code="1016"
                  show-all="N"
                  @change="handleUserTypeChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名称:" prop="id">
                <el-input
                  v-model="formData.userName"
                  placeholder="用户名称"
                  :readonly="formData.userType === '1' ? true : false"
                >
                  <template
                    v-if="formData.userType === '1' ? true : false"
                    #append
                  >
                    <el-button icon="Search" @click="handleOpenStaffSelector" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户账号:" prop="userCode">
                <el-input
                  v-model="formData.userCode"
                  :maxlength="32"
                  :show-word-limit="true"
                  type="text"
                >
                  <template #append>
                    <el-button icon="Refresh" @click="handleUserNameChange" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码:" prop="phone">
                <el-input v-model="formData.phone" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户编号:" prop="labor">
                <el-input
                  v-model="formData.labor"
                  :maxlength="16"
                  :show-word-limit="true"
                  type="text"
                />
              </el-form-item>
            </el-col>
            <el-col v-if="state.operationAdd" :span="12">
              <el-form-item label="用户密码:" prop="password">
                <el-tooltip
                  :append-to-body="false"
                  class="item"
                  content="密码8~20，且必须包含大写字母、小写字母、<br/>数字及特殊符号,默认:Itsm@123"
                  :model-value="true"
                  placement="right"
                  raw-content
                >
                  <el-input
                    v-model="formData.password"
                    :maxlength="20"
                    :show-word-limit="true"
                    type="text"
                  />
                </el-tooltip>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6">
          <el-form-item label="" prop="avatarImg">
            <el-avatar
              :size="100"
              :src="formData.avatar"
              style="cursor: pointer"
              @click="openAvatarCropperDialog"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="有效期限:" prop="validDate">
            <el-date-picker
              v-model="formData.validDate"
              :editable="false"
              placeholder="请选择有效期限"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="用户状态:" prop="status">
            <DictSelect
              ref="userStatusRef"
              :default-value="formData.status"
              dict-code="1000"
              show-all="N"
              @change="handleUserStatusChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="所属部门:" prop="mainDeptId">
            <el-cascader
              ref="mainDeptRef"
              v-model="formData.mainDeptId"
              clearable
              :collapse-tags="true"
              :options="cascaderOptions.dataList"
              :placeholder="formData.mainDeptName || '请选择所属部门'"
              :props="cascaderOptions.props"
              :show-all-levels="false"
              @change="handelMainDeptChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否可删除:" prop="ifAllowDelete">
            <el-radio v-model="formData.ifAllowDelete" label="Y"
              >允许删除</el-radio
            >
            <el-radio v-model="formData.ifAllowDelete" label="N"
              >不允许删除</el-radio
            >
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户角色:" prop="roleIds">
            <el-input
              v-model="formData.roleNames"
              placeholder="请选择用户角色"
              :readonly="true"
            >
              <template #append>
                <el-button icon="Search" @click="handleOpenRolePicker" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
      <el-button
        :disabled="state.readonly"
        icon="circle-check"
        type="primary"
        @click="save"
      >
        确 定
      </el-button>
    </template>
    <StaffPicker
      ref="staffRef"
      :ingore-binding="true"
      :multiple="false"
      title="选择员工"
      width="60%"
      @change="handleUserSelect"
    />
    <RolePicker ref="roleRef" width="70%" @change="handleRoleSelect" />
    <PictureCropper ref="vabCropperRef" @confirm="handleCropperConfirm" />
  </el-dialog>
</template>

<script setup name="UserEdit">
import dayjs from "dayjs";
import { useMessage } from "@/hooks/message";
import { addUser, updateUser, validUserCode } from "@/api/admin/org/sysuser/";
import { queryDeptTree } from "@/api/admin/org/dept/";
import { validMobilePhone, validPassword } from "@/utils/rules";
import StaffPicker from "@/components/staffPicker.vue";
import RolePicker from "@/components/rolePicker.vue";
import PictureCropper from "@/components/pictureCropper.vue";
import { useCascader } from "@/hooks/cascader";
import avatarDefaultImg from "@/assets/cropper_images/user.gif";
import pinyin from "js-pinyin";

const props = defineProps({
  title: {
    type: String,
    default: "用户"
  },
  width: {
    type: String,
    default: "20%"
  },
  model: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(["confirm"]);

const formRef = ref(null);
const mainDeptRef = ref(null);
const userStatusRef = ref(null);
const userTypeRef = ref(null);
const roleRef = ref(null);
const staffRef = ref(null);
const vabCropperRef = ref(null);
const formData = ref({
  id: "",
  userName: "",
  userCode: "",
  phone: "",
  labor: "",
  ifAllowDelete: "Y",
  validDate: dayjs(new Date()).add(1, "year").format("YYYY-MM-DD"),
  password: "Itsm@123",
  userType: "0",
  status: "0",
  roleIds: "",
  roleNames: "",
  mainDeptId: "",
  mainDeptName: "",
  avatar: avatarDefaultImg,
  avatarImg: ""
});

const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  readonly: false,
  operationAdd: false,
  formRules: {
    userCode: [
      { required: true, message: "用户账号不能为空", trigger: "blur" },
      {
        validator: async (rule, value, callback) => {
          const res = await validUserCode({
            id: formData.value.id,
            userCode: formData.value.userCode
          });
          if (res.code === 200) {
            callback();
          } else {
            callback(new Error(res.msg));
          }
        },
        trigger: "blur"
      }
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        validator: validPassword,
        trigger: "blur"
      }
    ],
    status: [{ required: true, message: "用户状态不能为空", trigger: "blur" }],
    roleIds: [{ required: true, message: "所属角色不能为空", trigger: "blur" }],
    validDate: [
      { required: true, message: "有效期限不能为空", trigger: "blur" }
    ],
    mainDeptId: [
      { required: true, message: "所属部门不能为空", trigger: "blur" }
    ],
    phone: [
      {
        validator: validMobilePhone,
        trigger: "blur"
      }
    ]
  }
});

const cascaderOptions = reactive({
  queryForm: { pid: "0" },
  props: {
    checkStrictly: true,
    multiple: false,
    emitPath: false,
    label: "text",
    value: "id",
    leaf: "leaf",
    lazy: true
  },
  queryFunction: queryDeptTree
});

const { queryCascaderData } = useCascader(cascaderOptions);

const show = (row, operation) => {
  console.log("show", row, operation);
  if (operation) {
    if (operation === "view") {
      state.dialogTitle = `${props.title}详情`;
      state.readonly = true;
    } else if (operation === "edit") {
      state.dialogTitle = `编辑${props.title}`;
    } else if (operation === "add") {
      state.dialogTitle = `新增${props.title}`;
      state.operationAdd = true;
    }
  }
  init(row);
  state.dialogVisible = true;
};

const init = row => {
  if (row && row.id) {
    //fetchData()
    formData.value = row;
    formData.value.userType = row.userType;
    if (!state.operationAdd) {
      formData.value.password = "";
    }
    if (formData.value.validDate) {
      formData.value.validDate = dayjs(formData.value.validDate).format(
        "YYYY-MM-DD"
      );
    }
  }
};

const handelMainDeptChange = val => {
  const items = mainDeptRef.value.getCheckedNodes();
  if (items && items.length > 0) {
    formData.value.mainDeptId = val;
    formData.value.mainDeptName = items[0].text;
    console.log(formData.value);
  }
};

const close = () => {
  formRef.value.resetFields();
  state.readonly = false;
  state.operationAdd = false;
  state.dialogTitle = props.title;
  formData.value = {
    operation: "",
    id: "",
    userName: "",
    userCode: "",
    password: "Itsm@123",
    userType: "0",
    roleIds: "",
    roleNames: "",
    phone: "",
    labor: "",
    validDate: dayjs(new Date()).add(1, "years").format("YYYY-MM-DD"),
    ifAllowDelete: "Y",
    status: "0",
    mainDeptId: "",
    mainDeptName: "",
    avatar: avatarDefaultImg,
    avatarImg: ""
  };
  state.dialogVisible = false;
};

const save = () => {
  formRef.value.validate(async (valid, callback) => {
    if (valid) {
      let data;
      if (state.operationAdd) {
        if (formData.value.userType === "1") {
          if (!formData.value.id) {
            useMessage().error("请选择员工");
            return;
          }
        }
        data = await addUser(formData.value);
      } else {
        const params = {
          id: formData.value.id,
          userName: formData.value.userName,
          userCode: formData.value.userCode,
          userType: formData.value.userType,
          roleIds: formData.value.roleIds,
          roleNames: formData.value.roleNames,
          phone: formData.value.phone,
          labor: formData.value.labor,
          validDate: formData.value.validDate,
          ifAllowDelete: formData.value.ifAllowDelete,
          status: formData.value.status,
          mainDeptId: formData.value.mainDeptId,
          mainDeptName: formData.value.mainDeptName,
          avatar: formData.value.avatar,
          avatarImg: formData.value.avatarImg
        };
        data = await updateUser(params);
      }
      if (data.code && data.code === 200) {
        useMessage().success(data.msg);
        emits("confirm", {});
        close();
      } else {
        useMessage().error(data.msg);
      }
    }
  });
};

const openAvatarCropperDialog = () => {
  vabCropperRef.value.show();
};

const handleCropperConfirm = value => {
  formData.value.avatarImg = value;
  formData.value.avatar = value;
};

const handleUserTypeChange = val => {
  formData.value.userType = val;
};

const handleUserStatusChange = val => {
  formData.value.status = val;
};

const handleOpenStaffSelector = () => {
  staffRef.value.show();
};

const handleOpenRolePicker = () => {
  roleRef.value.show();
};

const handleUserSelect = rows => {
  if (rows) {
    formData.value.id = rows[0].id;
    formData.value.userName = rows[0].userName;
    formData.value.phone = rows[0].mobilePhone;
    formData.value.labor = rows[0].labor;
    formData.value.mainDeptId = rows[0].mainDeptId;
    formData.value.mainDeptName = rows[0].mainDeptName;
  }
};

const handleRoleSelect = rows => {
  if (rows) {
    const roleIdList = [];
    const roleNameList = [];
    rows.forEach(item => {
      roleIdList.push(item.id);
      roleNameList.push(item.text);
    });
    formData.value.roleIds = roleIdList.join(",");
    formData.value.roleNames = roleNameList.join(",");
  }
};

const handleUserNameChange = () => {
  const userCode = pinyin.getCamelChars(formData.value.userName);
  formData.value.userCode = userCode.toLowerCase();
};

defineExpose({
  show,
  close,
  save
});
</script>
<style lang="scss" scoped>
.el-input__inner {
  width: 140px;
}

.item {
  margin: 4px;
}

.right .el-tooltip__popper {
  padding: 18px 0px;
}
</style>
